from django.core.paginator import Paginator
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from home.models import ArticleCategory, Article, Comment
import logging
logger = logging.getLogger()


class IndexView(View):
    def get(self,request):
        tit=ArticleCategory.objects.all()
        cid=request.GET.get('cid',1)
        try:
            info=ArticleCategory.objects.get(id=cid)#分类列表
        except Exception as e:
            logger.error(e)
            return HttpResponseBadRequest('无此分类')
        list=Article.objects.filter(category=info)#信息
        #分页
        page=request.GET.get('page',1)#第几页
        lit=request.GET.get('lit',3)#一页几条
        p = Paginator(list, lit)#分页对象
        try:
            pp = p.page(page)#分页后
        except Exception as e:
            pp = p.page(1)
        page=int(page)
        indexs = Article.objects.distinct().order_by('-total_views')[0:2]
        return render(request,'index.html',{'tit':tit,'info':info,'list':list,'pp':pp,'p':p,'page':page,'indexs':indexs})

class write(View):
    def get(self,request):
        a =ArticleCategory.objects.all()
        return render(request,'writeb.html',{'a':a})

    def post(self, request):
# 1、接收数据
        user = request.user
        avatar = request.FILES.get('avatar')
        title = request.POST.get('title')
        category_id = request.POST.get('category')
        tags = request.POST.get('tags')
        sumary = request.POST.get('sumary')
        content = request.POST.get('content')
        print(user,avatar,title,category_id,tags,sumary,content)
        if not all([avatar,title,category_id,tags,sumary,content]):
            return HttpResponseBadRequest("参数不全")

        try:
            category = ArticleCategory.objects.filter(pk=category_id).first()
        except ArticleCategory.DoesNotExist:
            return HttpResponseBadRequest('没有该分类信息')

        try:
            Article.objects.create(author=user, avatar=avatar, title=title, category_id=category_id, tags=tags,
                                   sumary=sumary, content=content)
        except Exception as e:
            logger.error(e)
            print(e)
            return HttpResponseBadRequest('发布失败，请稍后重试')
# 4、跳转到指定页面
        return redirect(reverse('home:index'))


class DetailView(View):
    def get(self,request):
        art_id=request.GET.get('art_id')
        try:
            art=Article.objects.get(id=art_id)
        except Article.DoesNotExist:
            return render(request,'404.html')
        art.total_views += 1
        art.save()
        # 评论
        pp = Comment.objects.filter(article_id=art_id).order_by('-created_time')
        list = Article.objects.filter(author=art.author)[0:3]
        return render(request,'details.html',{'art':art,'pp': pp,'list':list})

    def post(self, request):
        id = request.POST.get('id')  # 文章id
        content = request.POST.get('content')
        user = request.user
        try:  # 文章是否存在
            art = Article.objects.get(id=id)
        except Exception as e:
            return render(request, '404.html')
        if user and user.is_authenticated:  # 用户是否登录
            try:
                Comment.objects.create(content=content, article_id=id, user=user)
                art.comments_count += 1  # 评论量+1
                art.save()
            except Exception as e:
                return HttpResponse('发表失败')
            return redirect(reverse('home:detail') + "?art_id=" + id)
        else:
            return redirect(reverse("users:login"))




